package com.crm.config;

import com.crm.uilt.PaperServiceExceptionType;
import com.crm.uilt.RestResult;
import com.crm.uilt.Status;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjd
 * @Title:
 * @Description: 全局异常拦截器
 * @date 2021/4/211:50
 */
@RestControllerAdvice
//@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object logicExceptionHandler(HttpServletRequest request, Exception e, HttpServletResponse response) {
        RestResult result = new RestResult();
        //拦截validation验证的异常
        logger.error("{e:}"+e);
        if (e instanceof ConstraintViolationException) {
            String message = ((ConstraintViolationException) e).getConstraintViolations().iterator().next().getMessage();
            result.setCode(Integer.parseInt(message.substring(0, 4)));
            result.setDesc(message.substring(5));
        } else if(e instanceof ApiResultException){ //拦截自定义异常
            ApiResultException apiResultException = (ApiResultException) e;
            result.setCode(Integer.parseInt(apiResultException.getCode()));
            result.setDesc(apiResultException.getErrorMsg());
        } else {//拦截总异常
            logger.error("系统异常:" + e.getMessage(), e);
            result.setCode(-900);
            result.setDesc("系统异常");
        }
        return result;
    }
    /**
     *  校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validationBodyException(MethodArgumentNotValidException exception){
        //对校验错误信息进行封装，并输出到日志
        //RestResult result = new RestResult();
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p ->{

                FieldError fieldError = (FieldError) p;
                logger.error(PaperServiceExceptionType.VALID_ERROR+"：数据校验错误 : object{"+fieldError.getObjectName()+"},field{"+fieldError.getField()+
                        "},errorMessage{"+fieldError.getDefaultMessage()+"}");
                errorMessage.append("object{");
                errorMessage.append(fieldError.getObjectName()+"},field{");
                errorMessage.append(fieldError.getField()+"},errorMessage{");
                errorMessage.append(fieldError.getDefaultMessage()+"}");
            });

        }
        //封装错误到响应信息
        RestResult response = new RestResult();
        //Map<String,Object> map=new HashMap();
        //map.put("ErrorCode",PaperServiceExceptionType.VALID_ERROR);
       // map.put("Message",errorMessage.toString());
        //map.put("Body",PaperServiceExceptionType.VALID_ERROR+":传入数据错误"+errorMessage.toString());
        response.setData(errorMessage.toString());
        response.setCode(Status.PARAMETER_ERROR.code);
        response.setDesc(Status.PARAMETER_ERROR.message);
        return response;
    }

}

